package com.hm.rabitmq.route;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

/**
 * @author shishun.wang
 * @date 2016年12月9日 下午2:49:00
 * @version 1.0
 * @describe 保存日志
 */
public class SaveLog {

	private static final String EXCHANGE_NAME = "DIRECT_LOGS";

	private static final String[] LOG_LEVEL = { "error" };

	public static void main(String[] args) {
		try {
			ConnectionFactory factory = new ConnectionFactory();
			factory.setHost("115.28.66.183");

			Connection connection = factory.newConnection();
			Channel channel = connection.createChannel();
			// 创建一个名叫logs、类型是fanout的交换机(fanout类型的交换机会将消息广播给所有与其绑定的队列)
			channel.exchangeDeclare(EXCHANGE_NAME, "direct");
			// 创建一个临时队列。队列的名称是随机生成的,当断开连接时，队列会被自动删除。
			String queueName = channel.queueDeclare().getQueue();
			for (String logLevel : LOG_LEVEL) {
				channel.queueBind(queueName, EXCHANGE_NAME, logLevel);
			}

			QueueingConsumer consumer = new QueueingConsumer(channel);
			// 关闭消息应答模式
			channel.basicConsume(queueName, true, consumer);

			System.out.println("waiting for logs....");
			while (true) {
				QueueingConsumer.Delivery delivery = consumer.nextDelivery();
				String log = new String(delivery.getBody());
				// 打印日志等级
				String routingKey = delivery.getEnvelope().getRoutingKey();

				// 保存日志到文件(模拟)
				System.out.println("print the log:" + log);
				System.out.println("routingKey is:" + routingKey);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
